from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from .models import p_file,p_user_file,p_user_manage
from django.contrib.auth.models import User
from users.models import UserProfile
from datetime import datetime
from django.db import connection, transaction
from django.contrib.auth.decorators import login_required

import json
import os
import string
import random

#文档查看
# Create your views here.


@login_required(login_url='/login')
def pdfshow(request):
    p_name = request.user
    r_pdf_list = []
    try:
        p_id = UserProfile.objects.filter(name=p_name).values_list("user_id")[0][0]
        pdf_list_sql = """SELECT pf.pdf_name FROM p_user_file pu LEFT JOIN p_file pf ON pu.p_id = pf.id WHERE pu.u_id = %d""" % p_id
        cursor = connection.cursor()  # 获得一个游标(cursor)对象
        cursor.execute(pdf_list_sql)
        sel_data = cursor.fetchall()
        r_pdf_list = []
        for i in sel_data:
            r_pdf_list.append(i[0])
    except BaseException as b:
        _log_err = "pdfshowh函数异常 --》" + str(b)
        print(_log_err)
    finally:
        return render(request,'document/pdfshow.html',{"r_pdf_list":r_pdf_list})

@login_required(login_url='/login')
def pdfmanage(request):
    p_return_file, p_return_sel = file_sel()
    g_return_data = group_sel()
    return render(request, 'document/pdfmanage.html', {"p_file_list":p_return_file, "p_file_sel":p_return_sel, "g_group_list":g_return_data})

@csrf_exempt
@login_required(login_url='/login')
def pdfupload(request):
    if request.method == "POST":
        _status = 1
        pdf_d = r"D:\pycharms\django\operations\file\pdf"
        try:
            data = request.FILES.get('file')
            pdf_name = data.name
            print(pdf_name)
            pdf_status = pdf_name.split('.').pop()
            if pdf_status == "pdf":
                pdf_name_list = p_file.objects.filter(is_delete=0,pdf_name=pdf_name).values_list("id")
                if len(pdf_name_list) == 0:
                    pdf_f = os.path.join(pdf_d, pdf_name)
                    fobj = open(pdf_f, 'wb')
                    for chrunk in data.chunks():
                        fobj.write(chrunk)
                    fobj.close()
                    p_file.objects.create(pdf_name=pdf_name, pdf_file=str(pdf_f))

                    _status = 0
                else:
                    _status = 3
            else:
                _status = 2
        except BaseException as b:
            _log_err = "pdfupload函数异常 --》" + str(b)
            print(_log_err)
        finally:
            p_return_file, p_return_sel = file_sel()
            return HttpResponse(json.dumps({"status":_status, "p_file_list":p_return_file, "p_file_sel":p_return_sel}))

@csrf_exempt
@login_required(login_url='/login')
def pdffileops(request):
    if request.is_ajax():
        if request.method == "POST":
            _status=1
            try:
                fid = int(request.POST.get("fid"))
                p_file.objects.filter(id=fid).update(is_delete=0)
                _status=0
            except BaseException as b:
                _log_err="pdffileops函数报错 --》" + str(b)
                print(_log_err)
            finally:
                return HttpResponse()

@csrf_exempt
@login_required(login_url='/login')
def pdfgroupops(request):
    if request.is_ajax():
        if request.method == "POST":
            ptype = int(request.POST.get("type"))
            _status = 1
            if ptype == 0:
                pdata = eval(request.POST.get("data"))
                data_t = datetime.now()
                old_user_data = User.objects.values_list("username")
                old_user_list = []
                file_list = pdata["p_list"].split(',')
                for x in old_user_data:
                    old_user_list.append(x[0])
                user_list = []
                g_id = p_user_manage.objects.create(u_sum=int(pdata['u_sum']), u_list=file_list,
                                                    u_password=pdata["u_password"], createTime=data_t).id

                for i in range(int(pdata['u_sum'])):
                    user_json = {}
                    s_data = string.ascii_lowercase + string.digits
                    u_name = ''.join(random.sample(s_data,random.randint(6,10)))
                    if u_name not in old_user_list:
                        user_json["username"] = u_name
                        user_json["password"] = pdata["u_password"]
                        user_json["name"] = u_name
                        user_json["pdf_list"] = file_list
                        user_json["permissions_page"] = 9
                        user_json["g_id"] = g_id
                    user_list.append(user_json)
                print(user_list)
                ops_user(0, user_list)
                _status = 0
            if ptype == 1:
                p_id = int(request.POST.get("id"))
                print(p_id)
                ops_user(1, p_id)
                p_user_manage.objects.filter(id=p_id).update(is_delete=1)
                _status = 0
            if ptype ==2:
                pdata = eval(request.POST.get("data"))
                print(pdata)
                user_list = []
                for i in range(int(pdata['u_sum'])):
                    user_json = {}
                    old_user_data = User.objects.values_list("username")
                    old_user_list = []
                    for x in old_user_data:
                        old_user_list.append(x[0])
                    s_data = string.ascii_lowercase + string.digits
                    u_name = ''.join(random.sample(s_data, random.randint(6, 10)))
                    if u_name not in old_user_list:
                        user_json["username"] = u_name
                        user_json["password"] = pdata["u_password"]
                        user_json["name"] = u_name
                        user_json["pdf_list"] = eval(pdata["p_list"])
                        user_json["permissions_page"] = 9
                        user_json["g_id"] = pdata["g_id"]
                    user_list.append(user_json)
                print(user_list)
                z_num = int(pdata["u_sum"]) + int(pdata["old_num"])
                ops_user(0, user_list)
                p_user_manage.objects.filter(id=pdata["g_id"]).update(u_sum=z_num)
                _status = 0
            if ptype == 3:
                print(request.POST.get("data"))
                pdata = eval(request.POST.get("data"))
                new_pdf_list = pdata["p_list"].split(',')
                old_pdf_list = eval(p_user_manage.objects.filter(id=pdata["id"]).values_list("u_list")[0][0])
                add_list = [x for x in new_pdf_list if x not in old_pdf_list]
                for y in add_list:
                    pdf_id = p_file.objects.filter(pdf_name=y).values_list("id")[0][0]
                    u_id_list = p_user_file.objects.filter(g_id=pdata["id"]).values_list("u_id").distinct()
                    print(u_id_list)
                    for z in u_id_list:
                        p_user_file.objects.create(u_id=z[0],p_id=pdf_id,g_id=pdata["id"])
                p_user_manage.objects.filter(id=pdata["id"]).update(u_list=str(new_pdf_list))



            g_return_data = group_sel()
            return HttpResponse(json.dumps({"status":_status,"g_group_list":g_return_data}))

def ops_user(otype,ndata):
    try:
        if otype == 0:
            for odata in ndata:
                uom_user = User.objects.create_user(username=odata["username"], password=odata["password"])
                uom_user.save()
                profile = UserProfile()
                user_id = uom_user.id
                profile.user_id = user_id
                profile.name = odata["name"]
                profile.permissions_page = odata["permissions_page"]
                profile.save()
                for i in odata["pdf_list"]:
                    p_id = p_file.objects.filter(pdf_name=i).values_list("id")[0][0]
                    p_user_file.objects.create(u_id=user_id, p_id=p_id, g_id=odata["g_id"])
                print("%s用户创建成功！" % odata["username"])
        elif otype == 1:
            user_list = p_user_file.objects.filter(g_id=ndata).values_list("u_id")
            for i in user_list:
                UserProfile.objects.filter(user_id=int(i[0])).delete()
                User.objects.filter(id=int(i[0])).delete()
            p_user_file.objects.filter(g_id=ndata).delete()
    except BaseException as b:
        _log_err = "ops_user函数异常 --》" + str(b)
        print(_log_err)



def group_sel():
    g_return_list = []
    try:
        g_group_data = p_user_manage.objects.filter(is_delete=0).values_list('id', 'u_sum', 'u_list', 'u_password', 'createTime')
        g_list = ['id', 'u_sum', 'u_list', 'u_password', 'createTime']
        for item in g_group_data:
            g_json={}
            for i in range(len(g_list)):
                if g_list[i] == "createTime":
                    g_json[g_list[i]] = item[i].strftime('%Y-%m-%d %H:%M:%S')
                else:
                    g_json[g_list[i]] = item[i]
            g_user_sql = """select distinct uu.name from p_user_file AS puf LEFT JOIN u_userprofile as uu on puf.u_id = uu.user_id WHERE puf.g_id=%d""" % g_json["id"]
            cursor = connection.cursor()  # 获得一个游标(cursor)对象
            cursor.execute(g_user_sql)
            sel_aduit_data = cursor.fetchall()
            user_name = []
            for row in sel_aduit_data:
                user_name.append(row[0])
            g_json["user"] = user_name
            g_return_list.append(g_json)
            cursor.close()
    except BaseException as b:
        _log_err = "group_sel函数异常 --》" + str(b)
        print(_log_err)
    finally:
        return g_return_list

def file_sel():
    p_return_list = []
    p_sel_list = []
    try:
        p_file_data = p_file.objects.filter(is_delete=0).values_list("id", "pdf_name")
        p_file_list = ["id", "pdf_name"]
        p_return_list=[]
        p_sel_list = []
        for item in p_file_data:
            p_json = {}
            for i in range(len(p_file_list)):
                p_json[p_file_list[i]] = item[i]
            p_sel_list.append(p_json["pdf_name"])
            p_return_list.append(p_json)
        print(p_sel_list)
    except BaseException as b:
        _log_err = "file_sel函数异常 --》" + str(b)
        print(_log_err)
    finally:
        return p_return_list, p_sel_list